#include<iostream>
#include<cstring>
#include<sstream>
#include<queue>
// #define ONLINE_GUDGE
using namespace std;
const int N = 510, INF = 0x3f3f3f3f;

int m, n;
bool g[N][N];
int dist[N];
int stop[N];


int bfs()
{
    queue<int> q;
    q.push(1);
    memset(dist, INF, sizeof dist);
    dist[1] = 0;
    while(q.size())
    {
        int t = q.front(); q.pop();
        for(int i = 1; i <= n; i++)
        {
            if(g[t][i] && dist[i] > dist[t] + 1){
                dist[i] = dist[t] + 1;
                q.push(i);
            }
        }

    }
    return dist[n];
}


int main()
{
    #ifdef ONLINE_JUDGE

    #else
    freopen("./in.txt","r",stdin);
    #endif
    ios::sync_with_stdio(false);   
	cin.tie(0);

    cin >> m >> n;
    string line;
    getline(cin, line);// 第一行回车
    while(m--)
    {
        getline(cin, line);
        stringstream ss(line); // s-f
        int cnt = 0, p;
        while(ss >> p) stop[++cnt] = p;
        for(int j = 1; j <= cnt; j++)
            for(int k = j + 1; k <= cnt; k++)
                g[stop[j]][stop[k]] = true;
    }

    int ans = bfs();

    // for(int i = 1; i <= n; i++) printf("%d ", dist[i]);
    // cout << endl;
    
    if(ans == INF) printf("NO");
    else cout << max(ans-1, 0) << endl;
    return 0;
}